/*
* $Id: DatabaseManager.cpp 143 2010-09-09 19:55:18Z volok-aleksej@yandex.ru $
*
* Copyright 2008-2009 by Volokitin Alexey
* All rights reserved
*
*/
#include "Common/include.h"
#include "DatabaseManager.h"
#include "Database.h"
#include "Tables/InspectTable.h"
#include "Tables/EvacuationTable.h"
#include "Tables/FamiliesTable.h"
#include "Tables/FieldValuesTable.h"
#include "Tables/HousingsTable.h"
#include "Tables/TypesTable.h"
#include "Tables/JournalTable.h"
#include "Tables/PointsTable.h"
#include "Tables/QueenBeeTable.h"
#include "Tables/UserFieldsTable.h"

#include "Common/RefObject.h"
CRefObject<CDatabaseManager> g_DatabaseManager;
IDatabaseManager* IDatabaseManager::GetDatabaseManager(){
	return g_DatabaseManager.GetObject();
}

CDatabaseManager::CDatabaseManager(){}
CDatabaseManager::~CDatabaseManager()
{
	for(std::map<DatabaseHandle, IDatabase*>::iterator it = m_aOpenDatabases.begin(); it != m_aOpenDatabases.end(); it++)
		it->second->Free();
}

IDatabase* CDatabaseManager::OpenDatabase(const std::tstring& strNameDatabase)
{
	std::map<DatabaseHandle, IDatabase*>::iterator it = m_aOpenDatabases.find(strNameDatabase);
	if(it == m_aOpenDatabases.end()){
		CDatabase* pDatabase = new CDatabase(strNameDatabase);
		pDatabase->Open();
		it = m_aOpenDatabases.insert(m_aOpenDatabases.begin(), std::make_pair(DatabaseHandle(strNameDatabase), pDatabase)); 
	}
	else
		((int)(it->first.m_nClient))++;
	return it->second;
}

void CDatabaseManager::CloseDatabase(IDatabase* pDatabase)
{
	std::map<DatabaseHandle, IDatabase*>::iterator it = m_aOpenDatabases.find(pDatabase->GetDatabaseName());
	if(it != m_aOpenDatabases.end())
	{
		if(it->first.m_nClient == 0)
		{
			it->second->Free();
			m_aOpenDatabases.erase(it);
		}
		else
			((int)(it->first.m_nClient))--;
	}
}

void CDatabaseManager::Initialize(){
	//Create database if it doesn't exist
	IDatabase* pDatabase = OpenDatabase(JOURNAL_DATABASE_NAME);
	CFieldValuesTable table3;
	table3.CreateTable(pDatabase);
	CPointsTable table8;
	table8.CreateTable(pDatabase);
	CQueenBeeTable table6;
	table6.CreateTable(pDatabase);
	CFamiliesTable table2;
	table2.CreateTable(pDatabase);
	CEvacuationTable table1;
	table1.CreateTable(pDatabase);
	CHousingsTable table4;
	table4.CreateTable(pDatabase);
	CInspectTable table;
	table.CreateTable(pDatabase);
	CJournalTable table5;
	table5.CreateTable(pDatabase);
	CUserFieldsTable table7;
	table7.CreateTable(pDatabase);
	CTypeHousingsTable table9;
	table9.CreateTable(pDatabase);
	CTypeFrameTable table10;
	table10.CreateTable(pDatabase);
	CloseDatabase(pDatabase);
}